package manager

import (
	"encoding/json"
	"gmap-backend/internal/config"
	"gmap-backend/internal/config/secret"
	"gmap-backend/internal/util/httputil"
)

type PichostUploadResult struct {
	Code    string `json:"code"`
	ErrCode string `json:"errCode"`
	ErrMsg  string `json:"errMsg"`
	Data    string `json:"data"`
}

func UploadImg(config *config.AppConfig, filepath string) (bool, string) {
	succ, _, buf := httputil.UploadFileByBearerToken(filepath, secret.PICHOST_UPLOAD_IMG_URL, secret.PICHOST_UPLOAD_TOKEN, getUploadOption(config))
	if !succ {
		return false, ""
	}
	res := &PichostUploadResult{}
	json.Unmarshal(buf, res)
	if "0" == res.Code {
		return true, res.Data
	}
	return false, res.ErrMsg
}

func UploadAtt(config *config.AppConfig, filepath string) (bool, string) {
	succ, _, buf := httputil.UploadFileByBearerToken(filepath, secret.PICHOST_UPLOAD_ATT_URL, secret.PICHOST_UPLOAD_TOKEN, getUploadOption(config))
	if !succ {
		return false, ""
	}
	res := &PichostUploadResult{}
	json.Unmarshal(buf, res)
	if "0" == res.Code {
		return true, res.Data
	}
	return false, res.ErrMsg
}

func getUploadOption(appConfig *config.AppConfig) *httputil.UploadFileOption {
	return &httputil.UploadFileOption{
		Timeout:          config.UPLOAD_REQ_TIMEOUT,
		Ua:               config.DEFAULT_UA,
		MemBufThreadHold: 2 << 20,
		WorkDir:          appConfig.PathConfig.WorkDir,
		FileItemName:     "file",
	}
}
